package springboot.example.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springboot.example.springboot.common.BaseController;
import springboot.example.springboot.entity.Photo;
import springboot.example.springboot.service.PhotoService;
import springboot.example.springboot.service.QiNiuPhotoService;
import springboot.example.springboot.tools.MyExecption;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("/user")
@Controller
public class UserController extends BaseController {

    @Resource
    private QiNiuPhotoService qiNiuPhotoService;
    @Resource
    private PhotoService photoService ;

    @PostMapping(value = "qiNiuUpload")
    @ResponseBody
    public String qiNiuUpload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response, Model model){
        if (file == null) {

            return fail("上传失败,请更换图片重试");
        }

        if(!file.getContentType().equals("image/png") && !file.getContentType().equals("image/jpeg")  ){
            return fail("文件类型错误,请上传图片类型");
        }
        String fileName = null;

        try {
            fileName =  qiNiuPhotoService.uploadPhoto(file);
        } catch (MyExecption myExecption) {
            return fail(myExecption.getMessage());
        }

        model.addAttribute("path",fileName);
        return success("上传图片成功!!",model);
    }

    @GetMapping("/addPhoto")
    public String addPhoto(){
        return "test/addPhoto";
    }

    @PostMapping("/addPhoto")
    @ResponseBody
    public String addPhoto(Photo photo){
        try {
            photoService.save(photo);
        } catch (MyExecption myExecption) {
            return fail(myExecption.getMessage());
        }
        return success("上传成功！");
    }
}
